package cn.itcast.bos.web.action.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.ICourierService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {
    private Courier courier = new Courier();

    @Override
    public Courier getModel() {
        // TODO Auto-generated method stub
        return courier;
    }

    // 注入service
    @Autowired
    private ICourierService courierService;

    // 添加取派员
    @Action(value = "courier_save", results = {
            @Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
    public String saveCourier() {
        courierService.saveCourier(courier);
        System.out.println("添加取派员成功。。。");
        return SUCCESS;
    }

    // 分页查询取派员信息
    // 使用属性驱动得到page（当前页码）rows（查询条数）
    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    // 分页条件查询取派员信息
    @Action(value = "courier_pageQuery", results = { @Result(name = "success", type = "json") })
    public String pageQueryCourier() {
        Pageable pageable = new PageRequest(page - 1, rows);
        // 添加条件查询
        Specification spec = new Specification<Courier>() {
            /*
             * 构造条件查询方法。如果返回null，则无条件查询 root:条件表达式，相当于name=？ query：构造简单条件查询返回，相当于where cb：构造复杂条件查询
             */
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // 定义集合将条件放入
                List<Predicate> predicates = new ArrayList<Predicate>();
                // 根据工号查询
                // isEmpty判断某字符串是否为空，为空的标准是 str==null 或 str.length()==0
                // 判断字符串是否不为空且长度不为0且不由空白符(whitespace) 构成，
                if (StringUtils.isNotBlank(courier.getCourierNum())) {
                    Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
                    predicates.add(p1);
                }
                // 根据所属单位查询
                if (StringUtils.isNotBlank(courier.getCompany())) {
                    Predicate p2 = cb.like(root.get("company").as(String.class), "%" + courier.getCompany() + "%");
                    predicates.add(p2);
                }
                // 根据快递员类型查询
                if (StringUtils.isNotBlank(courier.getType())) {
                    Predicate p3 = cb.equal(root.get("type").as(String.class), courier.getType());
                    predicates.add(p3);
                }
                // 多表查询，关联standard表 根据取派标准
                Join<Object, Object> rootStandard = root.join("standard", JoinType.INNER);
                if (courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())) {
                    Predicate p4 = cb.like(rootStandard.get("name").as(String.class),
                            "%" + courier.getStandard().getName() + "%");
                    predicates.add(p4);
                }
                // and中是可变参数相当于数组，new Predicate[0]相当与传入Predicate类型
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        Page<Courier> pages = courierService.pageQueryCourier(spec, pageable);
        // 返回页面数据 total rows
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", pages.getTotalElements());
        map.put("rows", pages.getContent());

        ActionContext.getContext().getValueStack().push(map);
        return SUCCESS;
    }

    // 修改取派员状态
    // 属性驱动获得ids（所有id）
    private String ids;

    public void setIds(String ids) {
        this.ids = ids;
    }

    @Action(value = "courier_delBatch", results = {
            @Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
    public String delCourier() {
        // 按照，分割得到所有的id
        String[] idArray = ids.split(",");
        courierService.delCourier(idArray);
        return SUCCESS;
    }

    // 查询没有排班的快递员findnoassociation
    @Action(value = "courier_findnoassociation", results = { @Result(name = "success", type = "json") })
    public String findNoAssociation() {
        List<Courier> couriers = courierService.findNoAssociation();
        ActionContext.getContext().getValueStack().push(couriers);
        return SUCCESS;
    }
}
